# 2.1 导入蓝图对象
from flask import render_template, current_app, session, jsonify, request, g, abort, redirect

from info import constants, db
from info.models import User, News, Category, Comment
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blue


@profile_blue.route('/other_news_list')
def other_news_list():
    """返回指定用户的发布的新闻"""

    # 1. 取参数
    other_id = request.args.get("user_id")
    page = request.args.get("p", 1)

    # 2. 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not other:
        return jsonify(errno=RET.NODATA, errmsg="当前用户不存在")

    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blue.route('/other_info')
@user_login_data
def other_info():

    user = g.user

    # 去查询其他人的用户信息
    other_id = request.args.get("user_id")

    if not other_id:
        abort(404)

    # 查询指定id的用户信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    is_followed = False
    # if 当前新闻有作者，并且 当前登录用户已关注过这个用户
    if other and user:
        # if user 是否关注过 news.user
        if other in user.followed:
            is_followed = True

    data = {
        "is_followed": is_followed,
        "user": g.user.to_dict() if g.user else None,
        "other_info": other.to_dict()
    }
    return render_template('news/other.html', data=data)


@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {"users": user_dict_li,
            "total_page": total_page,
            "current_page": current_page
            }
    return render_template('news/user_follow.html', data=data)


@profile_blue.route('/news_list')
@user_login_data
def user_news_list():
    # 获取页数
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='页码错误')

    user = g.user
    news_model_list = []
    current_page = 1
    total_page = 1
    try:
        paginates = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_model_list = paginates.items
        # 获取当前页
        current_page = paginates.page
        # 获取总页数
        total_page = paginates.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news in news_model_list:
        news_dict_li.append(news.to_review_dict())
    data = {"news_list": news_dict_li,
            "total_page": total_page,
            "current_page": current_page
            }
    return render_template('news/user_news_list.html', data=data)


# @profile_blue.route('/news_release', methods=['GET', 'POST'])
# @user_login_data
# def news_release():
#     if request.method == "GET":
#         categories = []
#         try:
#             # 获取所有的分类数据
#             categories = Category.query.all()
#         except Exception as e:
#             current_app.logger.error(e)
#
#         # 定义列表保存分类数据
#         categories_dicts = []
#
#         for category in categories:
#             # 获取字典
#             cate_dict = category.to_dict()
#             # 拼接内容
#             categories_dicts.append(cate_dict)
#
#         # 移除`最新`分类
#         categories_dicts.pop(0)
#         # 返回内容
#         data = {
#             "categories": categories_dicts
#         }
#         return render_template('news/user_news_release.html', data=data)
#
#     # POST 提交，执行发布新闻操作
#
#     # 1. 获取要提交的数据
#     title = request.form.get("title")
#     source = "个人发布"
#     digest = request.form.get("digest")
#     content = request.form.get("content")
#     index_image = request.files.get("index_image")
#     category_id = request.form.get("category_id")
#     # 1.1 判断数据是否有值
#     if not all([title, source, digest, content, index_image, category_id]):
#         return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
#
#     # 1.2 尝试读取图片
#     # try:
#     #     index_image = index_image.read()
#     # except Exception as e:
#     #     current_app.logger.error(e)
#     #     return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
#
#     # 2. 将标题图片上传到七牛
#     try:
#         index_image_data = index_image.read()
#         # avatar = request.files.get("avatar").read()
#         image_file_name = storage(index_image_data)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
#
#     # 3. 初始化新闻模型，并设置相关数据
#     news = News()
#     news.title = title
#     news.digest = digest
#     news.source = source
#     news.content = content
#     news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_file_name
#     news.category_id = category_id
#     news.user_id = g.user.id
#     # 1代表待审核状态
#     news.status = 1
#
#     # 4. 保存到数据库
#     try:
#         db.session.add(news)
#         db.session.commit()
#     except Exception as e:
#         current_app.logger.error(e)
#         db.session.rollback()
#         return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
#     # 5. 返回结果
#     return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")

@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():

    if request.method == 'GET':

        # 查询新闻分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())

        # 去掉最新的分类数据
        category_dict_li.pop(0)

        data = {
            'categories': category_dict_li
        }
        return render_template('news/user_news_release.html', data=data)

    # POST发布

    # 1. 获取要提交的数据
    title = request.form.get("title")
    # 来源
    source = "个人发布"
    # 摘要
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([title, source, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # TODO 对分类ID-->int --> 查询数据库看是否有这个ID

    # 添加图片
    try:
        index_image_data = index_image.read()
        image_file_name = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 添加到数据库中
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    # 如果图片是别人的网站的数据,可以加上其他网站的前缀, 不加也可以
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_file_name
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blue.route('/collection')
@user_login_data
def user_collection():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页数据查询
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 收藏列表
    collection_dict_li = []
    for news in collections:
        collection_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": collection_dict_li
    }
    return render_template('news/user_collection.html', data=data)


@profile_blue.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    if request.method == "GET":

        return render_template('news/user_pass_info.html')
    # 1. 获取到传入参数
    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 获取当前登录用户的信息
    user = g.user

    # 3. 对比旧密码是否正确
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg="密码错误")

    # 4. 设置新密码
    user.password = new_password

    return jsonify(errno=RET.OK, errmsg="OK")


@profile_blue.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    # POST
    # 1.获取信息
    # 2. 上传到云服务器（七牛云）
    # 将文件名存储到数据库中
    # 将图像的URL地址返回到前端
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})

    # 1. 获取到上传的文件
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

    # 2. 再将文件上传到七牛云
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 3. 将头像信息更新到当前用户的模型中

    # 设置用户模型相关数据
    user.avatar_url = key
    # 将数据保存到数据库-->只需要记录文件名
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")

    # 4. 返回上传的结果<avatar_url>
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    if request.method == 'GET':
        data = {
            'user': g.user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    # POST 请求
    # 1.获取参数
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    # 2 参数校检
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='性别不对')

    # 3 逻辑处理
    user = g.user
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    # 跟新session信息
    session['nick_name'] = nick_name

    return jsonify(errno=RET.OK, errmsg='OK')


@profile_blue.route('/info')
@user_login_data
def user_info():

    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user': g.user.to_dict()
    }
    return render_template('news/user.html', data=data)
